import * as React from "react";
import store from "../../store";
import "./index.less";
export interface RouteLinkProps {
  url: string;
  children: any;
}

export interface RouteLinkState {}
/**菜单项接口 */
interface IMainMenuItem {
  id: string;
  /**菜单名 */
  name: string;
  key: string;
  pageId: string;
  parentId: string;
  parentkey: string;
  pathName: string;
  treeId: string;
}
class RouteLink extends React.Component<RouteLinkProps, RouteLinkState> {
  componentWillMount() {
    //
  }
  //判断数组中是否存在该项
  hasmMenuPage = (arr: MenuPageData[], item: IMainMenuItem) => {
    for (let i = 0; i < arr.length; i++) {
      if (arr[i].key === item.id.toString()) {
        return true;
      }
    }
    return false;
  };

  getTargetMenu(pageId: string) {
    let menuUrlData: IMainMenuItem[] = this.getmenuUrlData();
    let menu: IMainMenuItem | null = null;
    menuUrlData.map((item: IMainMenuItem) => {
      if (item.pageId === pageId) {
        menu = item;
      }
      return item;
    });
    return menu;
  }
  //获取tab页菜单
  getMenuData = () => {
    let MenuData: MenuPageData[] | null = store.PageTab.MenuData;
    let prfdsf: MenuPageData[] = [];
    if (MenuData) {
      prfdsf = MenuData;
    }
    return prfdsf;
  };
  //获取所有可选的菜单
  getmenuUrlData = () => {
    let MenuData: IMainMenuItem[] | null = store.PageTab.menuUrlData;
    let prfdsf: IMainMenuItem[] = [];
    if (MenuData) {
      prfdsf = MenuData;
    }
    return prfdsf;
  };
  //跳转
  onLink() {
    let urlToArr = this.props.url.split("/");
    let len = urlToArr.length;
    switch (len) {
      case 3: //正常页面跳转
        let menu: any = this.getTargetMenu(urlToArr[2]);
        if (menu) {
          let MenuData: MenuPageData[] = this.getMenuData();
          console.log(MenuData);
          console.log(menu);
          let item = {
            content: "/" + menu.pathName + "/" + menu.pageId,
            key: menu.id.toString(),
            pageId: menu.pageId,
            title: menu.name,
          };
          //如果页签列表中已存在此项，就不加入
          if (!this.hasmMenuPage(MenuData, menu)) {
            MenuData.push(item);
          }
          store.PageTab.setMenuData(MenuData);
          store.PageTab.setActiveKey(menu.id.toString());
          window.location.hash = "#/Portal/" + menu.pageId;
        }
        break;

      default:
        break;
    }
  }
  render() {
    return (
      <div
        className="RouteLink"
        onClick={() => {
          this.onLink();
        }}
      >
        {this.props.children}
      </div>
    );
  }
}
interface MenuPageData {
  title: string;
  content: string;
  pageId: string;
  key: string;
}
export default RouteLink;
